<?
/**
* Tarpipe_PHP - An interface to tarpipe.com REST API
* @author Jose da Silva <jose@josedasilva.net>
* @since 2008/05/14
* @version 0.1
*
* <code>
* <?
* require_once("lib/Tarpipe_PHP.php");
*
* $key    =       "YOUR_WORKFLOW_KEY";
* $client =       new Tarpipe_PHP($key);
* $title  =       "Playing with tarpipe.com PHP_API";
* $image  =       "directory/someimage.jpg";
* $body   =       "Some body on you message";
* $client->upload($title,$body,$image);
* ?>
* </code>
*/

/**
* Exception class for NoKey Defined
*/
class NoKeyException extends Exception
{
	public function __construct() {
		parent::__construct("Tarpipe.com API requires a workflow key!", 0);
	}

	// custom string representation of object
	public function __toString() {
		return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
	}

}

/**
* Tarpipe_PHP - An interface to tarpipe.com REST API
*/


class Tarpipe_PHP {

	private $version	=	'0.1';

	/**
	* Tarpipe_PHP Api [Curl/Http]
	*/
	private	$api_type	=	'curl';

	/**
	* Tarpipe.com workflow api key
	*/
	public 	$workflow_key;

	/**
	* Tarpipe.com base URI rest communication url
	*/
	public	$base_uri	=	'http://rest.receptor.tarpipe.net:8000';

	/**
	* Title of the message
	*/
	public $title;

	/**
	* Body of the message
	*/
	public $body;

	/**
	* Image of the message
	*/
	public $image;

	/**
	* Tarpipe_PHP constructor
	* @param string $workflow_key	
	*/
	public function __construct($workflow_key)
	{
		$this->workflow_key	=	$workflow_key;
	}

	/**
	* Method to switch the communication type
	* @param string $api_type // Should be curl or http
	*/
	public function api_switch($api_type="curl")
	{
		$this->api_type		=	$api_type;
	}

	/**
	* Method to upload media to tarpipe.com, will throw an NoKeyException when no workflow key is set
	* @param string $title
	* @param string $body
	* @param string $image
	*/
	public function upload( $title, $body='', $image='')
	{
		$image_binary	=	file_get_contents($image,FILE_BINARY);
		if( FALSE === $image_binary )
		{
			$image_binary	=	"";
		}

		if(trim($this->workflow_key) == "")
		{
			throw new NoKeyException();
		}
		$this->{$this->api_type."_send"}( $title, $body, $image_binary);
	}

	/**
	* Method to handle curl media send to tarpipe.com
	*  @param string $title
	* @param string $body
	* @param string $image
	*/
	public function curl_send($title, $body, $image)
	{
		$parameters	=	array("title"=>$title,"body"=> $body,"image"=>$image);

		$ch = curl_init();
		
		curl_setopt($ch, CURLOPT_URL, $this->base_uri."?key=".$this->workflow_key);
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters);
		curl_setopt($ch, CURLOPT_HEADER, false);

		// grab URL and pass it to the browser
		$result = curl_exec ($ch);
		// close cURL resource, and free up system resources
		curl_close($ch);
		return $result;
	}
}

?>
